using UnityEngine;
using UnityEditor;
using System.IO;
using GameBaseFramework.Base;
using System.Collections.Generic;
using System;
using UnityEngine.UI;
using GameUnityFramework.Extensions;

public class SpriteImporter : EditorWindow
{
    private string directoryPath;
    private bool success = false;

    private List<string> History;

    Vector2 HistoryScroll = new Vector2();

    Vector2 TotalScroll = new Vector2();


    public Shader Shader { get; private set; }

    [MenuItem("Tools/聚合工具")]
    public static void ShowWindow()
    {
        var window = GetWindow<SpriteImporter>();
        window.titleContent = new GUIContent("聚合工具");
        window.Show();
    }

    private void OnGUI()
    {
        TotalScroll = GUILayout.BeginScrollView(TotalScroll);


        GUILayout.Label("------重新导入文件夹下的所有贴图------");
        GUILayout.Label("文件夹路径:");

        directoryPath = GUILayout.TextField(directoryPath);

        if (GUILayout.Button("获取当前目录"))
        {
            var select = Selection.activeObject;
            directoryPath = AssetDatabase.GetAssetPath(select);
        }
        if (Directory.Exists(directoryPath))
        {
            if (GUILayout.Button("重新导入当前文件夹下所有贴图"))
            {
                History = new();
                ProcessDirectory(directoryPath, ProcessSingleImage);
            }
        }
        else
        {
            GUILayout.Label("Directory does not exist.");
        }

        GUILayout.Label("  ");
        GUILayout.Label("  ");

        GUILayout.Label("-------重新导入选中的贴图------------");

        if (GUILayout.Button("重新导入选中的贴图"))
        {
            History = new();
            var selected = Selection.objects;
            foreach (var select in selected)
            {
                string path = AssetDatabase.GetAssetPath(select);
                ProcessSingleImage(path);
            }
            AssetDatabase.SaveAssets();
            AssetDatabase.Refresh();
        }

        GUILayout.Label("  ");
        GUILayout.Label("  ");


        GUILayout.Label("-------预制体替换BackGround------------");
        if (GUILayout.Button("预制体替换BackGround"))
        {
            History = new();
            var selected = Selection.objects;
            foreach (var select in selected)
            {
                string path = AssetDatabase.GetAssetPath(select);
                ProcessSingleBackGround(path);
            }
            AssetDatabase.SaveAssets();
            AssetDatabase.Refresh();
        }

        GUILayout.Label("  ");
        GUILayout.Label("  ");

        if (GUILayout.Button("清除结果"))
        {
            success = false;
            History = new();
        }


        GUILayout.Label("-------上次执行的结果---------------");
        HistoryScroll = GUILayout.BeginScrollView(HistoryScroll);

        if (success) GUILayout.Label("Success!");
        if (History != null && History.Count > 0)
        {
            int Max = History.Count > 100 ? 100 : History.Count;
            for (int i = 0; i < Max; i++)
            {
                GUILayout.Label(History[i]);
            }
        }

        GUILayout.EndScrollView();
        GUILayout.EndScrollView();
    }


    /// <summary>
    /// 处理单个Prefab下的所有Image组件
    /// </summary>
    /// <param name="path"></param>
    private void ProcessSingleBackGround(string path)
    {
        GameObject obj = AssetDatabase.LoadAssetAtPath(path, typeof(GameObject)) as GameObject; // 加载资源为Texture2D对象  
        if (obj != null)
        {
            var Images = obj.transform.GetComponentsInChildren<Image>();
            foreach (var image in Images)
            {
                if (image.sprite == null) continue;
                if (image.sprite.name == "Background")
                {
                    image.sprite = null;
                    Log($"{obj.name} : {image.name} Done!");
                    EditorUtility.SetDirty(obj);
                    AssetDatabase.SaveAssets();
                    AssetDatabase.Refresh();
                }
            };
        }
    }


    /// <summary>
    /// 处理文件夹下的所有Texture2D
    /// </summary>
    /// <param name="directoryPath"></param>
    private void ProcessDirectory(string directoryPath, Action<string> action)
    {
        Debug.Log(Directory.GetFiles(directoryPath, "*.png", SearchOption.AllDirectories).ToJson());
        foreach (var file in Directory.GetFiles(directoryPath, "*.png", SearchOption.AllDirectories))
        {
            action.Invoke(file);
            ProcessSingleImage(file);
        }
        success = true;
    }

    /// <summary>
    /// 处理单张贴图
    /// </summary>
    /// <param name="file"></param>
    private void ProcessSingleImage(string file)
    {
        string fullPath = file; // 完整的文件路径，包括文件名和扩展名  
        if (fullPath != null)
        {
            Texture2D texture = AssetDatabase.LoadAssetAtPath(fullPath, typeof(Texture2D)) as Texture2D; // 加载资源为Texture2D对象  
            if (texture != null)
            {
                // 取消mipmap选项的勾选
                TextureImporter textureImporter = AssetImporter.GetAtPath(fullPath) as TextureImporter;
                textureImporter.textureType = TextureImporterType.Sprite;
                textureImporter.spriteImportMode = SpriteImportMode.Single;
                textureImporter.mipmapEnabled = false;
                textureImporter.wrapMode = TextureWrapMode.Clamp;
                textureImporter.filterMode = FilterMode.Point;
                textureImporter.maxTextureSize = 2048;
                textureImporter.SaveAndReimport();


                AssetDatabase.ImportAsset(fullPath);
                History.Add(file);
            }
        }
    }

    /// <summary>
    /// 打印信息
    /// </summary>
    /// <param name="message"></param>
    private void Log(string message)
    {
        History.Add(message);
    }
}